<!--#layout name=blank-->
<div id="app">
  <div class="page-header">
    <h1 class="title">Form values</h1>
  </div>
  <kb-breadcrumb :breads="breads"></kb-breadcrumb>
  <div class="navbar navbar-default">
    <div class="container-fluid">
      <a v-show="selected.length" @click="onDelete" class="btn red navbar-btn"
        >Delete</a
      >
    </div>
  </div>
  <kb-table :data="docs" show-select :selected.sync="selected">
    <kb-table-column
      v-for="col in cols"
      :label="col"
      :prop="col"
    ></kb-table-column>
  </kb-table>
  <kb-pager
    v-if="model"
    :page-nr="model.pageNr"
    :total-pages="model.totalPages"
    @change="load"
  ></kb-pager>
</div>

<script>
  (function() {
    Kooboo.loadJS([
      "/_Admin/Scripts/components/kbTable.js",
      "/_Admin/Scripts/components/kbPager.js",
      "/_Admin/Scripts/components/kbBreadcrumb.js"
    ]);

    self = new Vue({
      el: "#app",
      data: function() {
        return {
          breads: [
            {
              name: "SITES"
            },
            {
              name: "DASHBOARD"
            },
            {
              name: Kooboo.text.common.Forms,
              url: Kooboo.Route.Form.ListPage
            },
            {
              name: Kooboo.text.common.data
            }
          ],
          selected: [],
          model: null
        };
      },
      mounted: function() {
        this.load();
      },
      computed: {
        cols: function() {
          var _col = [];
          if (this.model) {
            _.forEach(this.model.list, function(item) {
              _.forEach(Object.keys(item.values), function(key) {
                _col.indexOf(key) == -1 && _col.push(key);
              });
            });
          }
          return _col;
        },
        docs: function() {
          var docs = [];
          if (this.model) {
            _.forEach(this.model.list, function(item) {
              var model = {
                id: item.id
              };

              _.forEach(self.cols, function(col) {
                model[col] = item.values[col];
              });

              docs.push(model);
            });
          }
          return docs;
        }
      },
      methods: {
        load: function(page) {
          Kooboo.Form.Values({
            id: Kooboo.getQueryString("id"),
            pageNr: page
          }).then(function(res) {
            if (res.success) {
              self.model = res.model;
            }
          });
        },
        onDelete: function() {
          if (confirm(Kooboo.text.confirm.deleteItems)) {
            var ids = [];
            _.forEach(this.selected, function(item) {
              ids.push(item.id);
            });

            Kooboo.Form.DeleteValues({
              ids: JSON.stringify(ids)
            }).then(function(res) {
              if (res.success) {
                self.load();
              }
            });
          }
        }
      }
    });
  })();
</script>
